package com.esun.cheetah.view.setting;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.config.Language;
import com.esun.cheetah.view.setting.com.SetCommu;
import com.esun.util.Tools;

/**
 * 设置详细，定制比赛信息 com.esun.cheetah.view.setting.SetDetailsAct
 * 
 * @author 任付江; create at 2012-3-30 上午10:36:57
 */
public class SetDetailsAct extends Activity {
	/** 返回按钮 */
	private Button btBack;
	/** 总开关 */
	private CheckBox cbOpenTip;
	/** 铃声提示 */
	private CheckBox cbRingTip;
	/** 震动提示 */
	private CheckBox cbVibTip;
	/** 足球开场结束 */
	private CheckBox cbFootBeginOrEndTip;
	/** 足球进球提示 */
	private CheckBox cbFootGoalTip;
	/** 红牌 */
	private CheckBox cbRedCardTip;
	/** 赛前提醒*/
	private CheckBox cbPreGame;
	/** 设置开始时间 */
	private CheckBox cbChooseBeginTime;
	/** 选择结束时间 */
	private CheckBox cbChooseEndTime;
	/** 铃声的值 */
	private boolean isRing;
	/** 震动的值 */
	private boolean isVib;
	/** 足球开场结束 */
	private boolean isFootBeginOrend = false;
	/** 足球进球 */
	private boolean isGoal=false;
	/** 红牌 */
	private boolean isRed = false;
	/** 开赛前30分钟提醒*/
	private boolean isPreThrity;
	/** 记录状态是否改变 */
	private int isChange = 0;
	/** 是不需要保存改变没登陆的值 ring */
	private boolean isSaveRing = false;
	/** 是不需要保存改变没登陆的值 par */
	private boolean isSavePar = false;
	/** 是不需要保存改变没登陆的值 isVb */
	private boolean isSaveVb = false;
	/** 是不需要保存改变没登陆的值 FootBegin */
	private boolean isSaveFootBegin = false;
	/** 是不需要保存改变没登陆的值 isFootGoal */
	private boolean isSaveFootGoal = false;
	/** 是不需要保存改变没登陆的值 RedCard */
	private boolean isSaveRedCard = false;
	/** 是不需要保存开赛前30分钟提醒  */
	private boolean issavePreThrity = false;
	private ValuesManager valuesManager;
	/** 开始时间EditText */
	private EditText etBeginTime;
	/** 结束时间EditText */
	private EditText etEndTime;
	/** 开始时间标志位 */
	private boolean isbgTime;
	/** 结束时间标志位 */
	private boolean isEndTime;
	/** 读取preference里面的时间 */
	private SharedPreferences sharedPrefs;
	/** 开始时间 */
	private String beginTime;
	/** 结束时间 */
	private String endTime;
	/** 用户记住用户是否已经更改设置 */
	private int alter = 0;
	public static final String PROMP="设置已保存";
	Handler timeHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Config.COMMUNICATER_SUCCESS:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.custom_info_tip);
		initSharePreference();
		initViews();
	}

	private void initViews() {
		etBeginTime = (EditText) findViewById(R.id.etBeginTime);
		etBeginTime.setText(beginTime);
		etEndTime = (EditText) findViewById(R.id.etEndTime);
		etEndTime.setText(endTime);
		cbVibTip = (CheckBox) findViewById(R.id.cbVib);
		cbVibTip.setChecked(valuesManager.isVibrator());
		getPearValues();
		cbOpenTip = (CheckBox) findViewById(R.id.cbOpenTip);
		cbOpenTip.setChecked(valuesManager.isParent());
		cbOpenTip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				changeValues(Config.PCF, isChecked);
				isChange = 1;
				mainSwitch(isChecked);
			}
		});
		cbRingTip = (CheckBox) findViewById(R.id.cbRing);
		cbRingTip.setChecked(valuesManager.isRing());
		cbRingTip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				changeValues(Config.RING_PREFERENCE, isChecked);
				isRing = isChecked;
				 isChange = 1;
				
				cbOpenTip.setChecked(valuesManager.value(SetDetailsAct.this));
				if (isChecked) {
					cbVibTip.setChecked(false);
				}
			}
		});
		cbVibTip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				changeValues(Config.VIBRATOR_PREFERENCE, isChecked);
				isVib = isChecked;
				isChange = 1;
				
				cbOpenTip.setChecked(valuesManager.value(SetDetailsAct.this));
				if (isChecked) {
					cbRingTip.setChecked(false);
				}
			}
		});
		cbFootBeginOrEndTip = (CheckBox) findViewById(R.id.cbFootBeginOrEND);
		cbFootBeginOrEndTip.setChecked(valuesManager.isFbBegOrEnd());
		cbFootBeginOrEndTip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				changeValues(Config.FOOT_BEG_END_PREF, isChecked);
				isFootBeginOrend = isChecked;
				isChange = 1;
				
				cbOpenTip.setChecked(valuesManager.value(SetDetailsAct.this));
			}
		});
		cbFootGoalTip = (CheckBox) findViewById(R.id.cbFootGoal);
		cbFootGoalTip.setChecked(valuesManager.isGoal());
		cbFootGoalTip.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				changeValues(Config.FOOT_GOAL_PREF, isChecked);
				isGoal = isChecked;
				isChange = 1;
				
				cbOpenTip.setChecked(valuesManager.value(SetDetailsAct.this));
			}
		});
		cbRedCardTip = (CheckBox) findViewById(R.id.cbFootRedCard);
		cbRedCardTip.setChecked(valuesManager.isRedCard());
		cbRedCardTip.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				changeValues(Config.RED_CARD_PREF, isChecked);
				isRed = isChecked;
				isChange = 1;
				
				cbOpenTip.setChecked(valuesManager.value(SetDetailsAct.this));
			}
		});
		cbPreGame=(CheckBox) findViewById(R.id.cbPreGame);
		cbPreGame.setChecked(valuesManager.isPreGameThrityMinit());
		cbPreGame.setOnCheckedChangeListener(new OnCheckedChangeListener() {	
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				changeValues(Config.BEGIN_PRE_THRIT, isChecked);
				isPreThrity=isChecked;
				isChange = 1;
				
				cbOpenTip.setChecked(valuesManager.value(SetDetailsAct.this));
			}
		});
		cbChooseBeginTime = (CheckBox) findViewById(R.id.cbBeginTime);
		cbChooseBeginTime.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					isbgTime = true;
					createDialog("选择开始时间");
					alter = 1;
				}
			}
		});
		cbChooseEndTime = (CheckBox) findViewById(R.id.cbEndTime);
		cbChooseEndTime.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					isEndTime = true;
					alter = 1;
					createDialog("选择结束时间");
				}
			}
		});
		btBack = (Button) findViewById(R.id.btBack);
		btBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	/**
	 * 保存改变后的参数到preferences
	 * 
	 * @param key
	 * @param values
	 */
	private void changeValues(String key, boolean values) {
		SharedPreferences sharedPrefs = this.getSharedPreferences(Config.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
		Editor editor = sharedPrefs.edit();
		editor.putBoolean(key, values);
		editor.commit();
	}

	@Override
	protected void onPause() {
		super.onStop();
		if (!Tools.networkStatus(this)) {
			Tools.TipNetworkError(SetDetailsAct.this, Language.INTERNET_FAIL);
			return;
		}
		String ck = UserInfo.getUserInfo().getCk();
		if (ck != null && ck.equals("")&&(alter == 1||isChange==1)) {
			saveChanged();
			promp("没有登录，设置无效");
		} else {
			if (alter == 1 && isChange == 1) {
				communicator();
				promp(PROMP);
			} else {
				if (isChange == 1) {
					communicator();
					promp(PROMP);
				}
				if (alter == 1) {
					communicator();
					promp(PROMP);
				}
			}
		}
		alter = 0;
		isChange = 0;
	}

	/**
	 * 与服务器通讯
	 */
	private void communicator() {
		if (alter == 1) {
			new SetCommu(timeHandler, SetDetailsAct.this, sharedPrefs.getString(Config.BEGIN_TIME, "00:00"), sharedPrefs.getString(
					Config.END_TIME, "00:00")).startCommunicate();
			promp("设置已保存");
		}

	}

	/**
	 * 保存提醒设置的 改变值
	 */
	private void saveChanged() {
		valuesManager = new ValuesManager(this);
		if (isSaveRing != valuesManager.isRing()) {
			changeValues(Config.RING_PREFERENCE, isSaveRing);
		}
		if (isSavePar != valuesManager.isParent()) {
			changeValues(Config.PCF, isSavePar);
		}
		if (isSaveVb != valuesManager.isVibrator()) {
			changeValues(Config.VIBRATOR_PREFERENCE, isSaveVb);
		}
		if (isSaveFootBegin != valuesManager.isFbBegOrEnd()) {
			changeValues(Config.FOOT_BEG_END_PREF, isSaveFootBegin);
		}
		if (isSaveFootGoal != valuesManager.isGoal()) {
			changeValues(Config.FOOT_GOAL_PREF, isSaveFootGoal);
		}
		if (isSaveRedCard != valuesManager.isRedCard()) {
			changeValues(Config.RED_CARD_PREF, isSaveRedCard);
		}
		if(issavePreThrity !=valuesManager.isPreGameThrityMinit()){
			changeValues(Config.BEGIN_PRE_THRIT, issavePreThrity);
		}
	}

	/*
	 * 获得之前保存的值
	 */
	private void getPearValues() {
		isSaveRing = valuesManager.isRing();
		isSavePar = valuesManager.isParent();
		isSaveVb = valuesManager.isVibrator();
		isSaveFootBegin = valuesManager.isFbBegOrEnd();
		isSaveFootGoal = valuesManager.isGoal();
		isSaveRedCard = valuesManager.isRedCard();
		issavePreThrity=valuesManager.isPreGameThrityMinit();
	}

	private void initSharePreference() {
		valuesManager = new ValuesManager(this);
		sharedPrefs = this.getSharedPreferences(Config.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
		beginTime = sharedPrefs.getString(Config.BEGIN_TIME, "00:00");
		endTime = sharedPrefs.getString(Config.END_TIME, "23:59");
	}

	/**
	 * 总开关
	 * 
	 * @param isChecked
	 */
	private void mainSwitch(boolean isChecked) {
		if (isChecked) {
			if (isRing) {
				return;
			}
			if (isVib) {
				return;
			}
			if (isFootBeginOrend) {
				return;
			}
			if (isGoal) {
				return;
			}
			if (isRed) {
				return;
			}
			if (isPreThrity) {
				return;
			}
			cbRingTip.setChecked(true);
			cbVibTip.setChecked(true);
			cbFootBeginOrEndTip.setChecked(true);
			cbFootGoalTip.setChecked(true);
			cbRedCardTip.setChecked(true);
			cbPreGame.setChecked(true);
		} else {
			cbRingTip.setChecked(false);
			cbVibTip.setChecked(false);
			cbFootBeginOrEndTip.setChecked(false);
			cbFootGoalTip.setChecked(false);
			cbRedCardTip.setChecked(false);
			cbPreGame.setChecked(false);
		}
	}

	/**
	 * 时间选择对话框
	 */
	public void createDialog(String promp) {
		final Dialog inputPwdDialog = new Dialog(this, R.style.dialog);
		inputPwdDialog.getWindow().setContentView(R.layout.time_choose_dialog);
		TextView tvPromp = (TextView) inputPwdDialog.findViewById(R.id.tvChooseTimeTip);
		tvPromp.setText(promp);
		ListView lvTime = (ListView) inputPwdDialog.getWindow().findViewById(R.id.lvTime);
		Button btnCacel = (Button) inputPwdDialog.getWindow().findViewById(R.id.btnCancel);
		btnCacel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				inputPwdDialog.cancel();
			}
		});
		TimeAdapter timeAdapter = new TimeAdapter(SetDetailsAct.this, inputPwdDialog);
		lvTime.setAdapter(timeAdapter);
		inputPwdDialog.show();
	}

	/**
	 * 时间适配器 com.esun.cheetah.view.setting.TimeAdapter
	 * 
	 * @author 任付江 create at 2012-3-30 上午11:01:05
	 */
	public class TimeAdapter extends BaseAdapter {
		/** 上下文对象 */
		private Context context = null;
		/** 时间数组 */
		private String[] time = { "00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00",
				"11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00",
				"23:59" };
		/** 时间对话框 */
		private Dialog inputPwdDialog;

		public TimeAdapter(Context c, Dialog inputPwdDialog) {
			this.context = c;
			this.inputPwdDialog = inputPwdDialog;
		}

		@Override
		public int getCount() {
			return time.length;
		}

		@Override
		public Object getItem(int position) {
			return time[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater lif = LayoutInflater.from(context);
			convertView = lif.inflate(R.layout.time_ckview, null);
			final CheckedTextView ctb = (CheckedTextView) convertView.findViewById(R.id.chtvTime);
			beginTime = sharedPrefs.getString(Config.BEGIN_TIME, "00:00");
			endTime = sharedPrefs.getString(Config.END_TIME, "23:59");
			final String strTime = time[position];
			if (isbgTime && beginTime.equals(strTime) && etBeginTime.getText().toString().equals(strTime)) {
				ctb.setCheckMarkDrawable(context.getResources().getDrawable(R.drawable.btn_focused_popup_radiobtn_32x32));
				changeValues(Config.BEGIN_TIME, strTime);
			}
			if (isEndTime && strTime.equals(endTime) && etEndTime.getText().toString().equals(strTime)) {
				ctb.setCheckMarkDrawable(context.getResources().getDrawable(R.drawable.btn_focused_popup_radiobtn_32x32));
				changeValues(Config.END_TIME, strTime);
			}
			ctb.setText(strTime);
			ctb.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					ctb.setCheckMarkDrawable(context.getResources().getDrawable(R.drawable.btn_focused_popup_radiobtn_32x32));
					if (isbgTime) {
						changeValues(Config.BEGIN_TIME, strTime);
						etBeginTime.setText(strTime);
						isbgTime = false;
						cbChooseBeginTime.setChecked(false);
					}
					if (isEndTime) {
						changeValues(Config.END_TIME, strTime);
						isEndTime = false;
						etEndTime.setText(strTime);
						cbChooseEndTime.setChecked(false);
					}
					inputPwdDialog.cancel();
				}
			});
			return convertView;
		}
	}

	/**
	 * 保存改变后的参数到preferences
	 * 
	 * @param key
	 * @param values
	 */
	private void changeValues(String key, String values) {
		Editor editor = sharedPrefs.edit();
		editor.putString(key, values);
		editor.commit();
	}

	private void promp(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}
}
